// pages/home/activityDetail/activityContent/index.js
import {
  home
} from '../../../../api/index'
let leftHeight = 0,
  rightHeight = 0; //分别定义左右两边的高度
let query;
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    SeriesWayId: '',
    obj: {
      '0': 'DetailPosterUrl', //活动简介
      '1': 'IntroducePosterUrl', // 活动说明
      '2': "", // 作品专区
      '3': "AwardPosterUrl", // 获奖名单
      '4': "", // 创作
      '6': 'PrecautionPosterUrl' // 活动须知
    },
    id: '',
    activeTab: 0,
    list: [],
    leftList: [],
    rightList: [],
    listLoadStatus: 0,
    pullDownRefreshing: false,
    isRenderOver: true,
    IMGBASEURL: app.globalData.IMGBASEURL,
    tabList: [{
      val: 3,
      text: '推荐'
    }, {
      val: 0,
      text: '最新'
    }, {
      val: 1,
      text: '最热'
    }, {
      val: 2,
      text: '我的'
    }],
    tagActiveT: 3,
    loadImgNum: 0,
    aaNnmImag: 1
  },
  listPagination: {
    index: 0,
    num: 10,
  },

  //去登录
  shudLogin() {
    const popup = this.selectComponent("#popupid");
    popup.setData({
      visible: true,
      isNavBar: false,
    });
  },
  onChange(event) {
    console.log(event.detail.val);
    this.setData({
      SeriesWayId: event.detail.val
    })
    this.loadData(true)
  },
  goPage() {
    if (!wx.getStorageSync('token')) {
      this.shudLogin();
      return
    }
    wx.navigateTo({
      url: `/pages/h5Page/activityRegistration/index?id=${this.data.id}&JoinType=${this.data.data.JoinType}`,
    })
  },
  onImgLoad() {
    if (this.data.aaNnmImag == this.data.loadImgNum) {
      for (const key in this.data.obj) {
        wx.createSelectorQuery().select(`#${this.data.obj[key]}`).boundingClientRect((rect) => {
          if (rect && rect.top) {
            this.setData({
              [this.data.obj[key]]: rect.top - 36 - 32
            })
          }
        }).exec()
      }
      wx.hideLoading()
    }
    this.setData({
      aaNnmImag: this.data.aaNnmImag + 1
    })
  },
  toScroll(num) {
    if (this.data[this.data.obj[num]]) {
      wx.pageScrollTo({
        scrollTop: this.data[this.data.obj[num]],
        duration: 300
      });
    }
  },
  clickTab(e) {
    let index = e.target.dataset.index
    this.toScroll(index)
    if (index !== this.data.activeTab) {
      this.setData({
        activeTab: index
      })
    }
    if (index == 2) {
      wx.pageScrollTo({
        scrollTop: 0,
      });
      this.loadData()

    }
  },
  onTabsChange(e) {
    let tagActiveT = e.target.dataset.index
    this.setData({
      tagActiveT
    })
    this.loadData(true)
  },
  // onPullDownRefresh() {
  //   if (this.data.listLoadStatus === 0 && this.data.isRenderOver) {
  //     this.loadData(true)
  //   } else {
  //     wx.stopPullDownRefresh()
  //   }
  // },
  onReachBottom() {
    if (this.data.listLoadStatus === 0 && this.data.isRenderOver && this.data.activeTab == 2) {
      this.loadData();
    }
  },

  async loadData(fresh = false) {
    if (fresh) {
      wx.pageScrollTo({
        scrollTop: 0,
      });
    }
    this.setData({
      listLoadStatus: 1
    });
    const pageSize = this.listPagination.num;
    let pageIndex = this.listPagination.index + 1;
    let nextList = []
    if (fresh) {
      pageIndex = 1;
      this.setData({
        leftList: [],
        rightList: []
      })
      this.setData({
        isShowHistory: false
      })
    }
    try {
      const res = await home.getallcontent({
        "PageIndex": pageIndex, //第几页
        "PageSize": pageSize, //每页数据量
        "CreationSeriesId": this.data.id,
        "CotentSort": this.data.tagActiveT,
        "SeriesWayId": this.data.SeriesWayId
      })
      nextList = res.Result.Datas
      this.setData({
        listLoadStatus: this.data.list.length == res.Result.TotalCount ? 2 : 0,
      });
      this.setData({
        pageLoading: false,
      });
      wx.stopPullDownRefresh();
      this.setData({
        list: fresh ? nextList : this.data.list.concat(nextList),
      });
      const {
        leftList,
        rightList
      } = this.data;
      query = wx.createSelectorQuery().in(this);
      for (let index = 0; index < nextList.length; index++) {
        if (index == 0) {
          this.data.isRenderOver = false
        }
        const item = nextList[index];
        if (this.data.listLoadStatus == 1) {
          this.data.isRenderOver = true
          return
        }
        if (this.data.leftList.length === 0 && this.data.rightList.length === 0) {
          leftList.push(item)
        } else {
          leftHeight <= rightHeight ? leftList.push(item) : rightList.push(item); //判断两边高度，来觉得添加到那边
        }
        await this.getBoxHeight(leftList, rightList);
        if (index == nextList.length - 1) {
          this.data.isRenderOver = true
        }
      }
      this.listPagination.index = pageIndex;
      this.listPagination.num = pageSize;
    } catch (error) {
      this.setData({
        listLoadStatus: 3
      });
    }
  },
  onReTry() {
    this.loadData(true);
  },
  getBoxHeight(leftList, rightList) { //获取左右两边高度
    return new Promise((resolve, reject) => {
      this.setData({
        leftList,
        rightList
      }, () => {
        query.select('#left').boundingClientRect();
        query.select('#right').boundingClientRect();
        query.exec((res) => {
          setTimeout(() => {
            leftHeight = res[0].height; //获取左边列表的高度
            rightHeight = res[1].height; //获取右边列表的高度
            resolve();
          }, 0)
        });
      });
    })
  },
  onLoad(options) {
    if (options.name) {
      wx.setNavigationBarTitle({
        title: decodeURI(options.name)
      })
    }

    wx.showLoading()
    this.setData({
      id: options.id
    })
    home.getseriesdetail({
      "ID": options.id,
      "ActivePort": 3
    }).then(res => {
      let num = 0
      res.Result.TabButtonList.forEach(element => {
        if (res.Result[this.data.obj[element.ButtonType]]) num++
      });
      console.log(res.Result.WayList);
      if (res.Result.WayList && res.Result.WayList.length > 0) {
        res.Result.WayList = [{
          ID: '',
          Name: '全部作品'
        }, ...res.Result.WayList]
      }
      this.setData({
        data: res.Result,
        loadImgNum: num
      })
      wx.setNavigationBarTitle({
        title: res.Result.Title
      })

    })
  },
  scrollDebounceTimer: null,
  onPageScroll: function (e) {
    if (e.scrollTop >= 150) {
      // 每次触发事件时先清除之前可能存在的定时器
      if (this.scrollDebounceTimer) {
        clearTimeout(this.scrollDebounceTimer);
      }
      // 将isScroll设置为true
      this.setData({
        isScroll: true
      });
      // 设置新的定时器，两秒后将isScroll设置为false
      this.scrollDebounceTimer = setTimeout(() => {
        this.setData({
          isScroll: false
        });
        // 定时器执行完后将存储定时器的变量重置为null
        this.scrollDebounceTimer = null;
      }, 2000);
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})